package com.kly.sc.api.application.controller.order;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.base.services.redis.RedisClient;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.HttpUtil;
import com.google.common.collect.Maps;
import com.kly.dto.MemberDto;
import com.kly.dto.ReduceBenefitsDto;
import com.kly.dto.TOrderDto;
import com.kly.dto.UserVasPurchasesDto;
import com.kly.enums.Benefits;
import com.kly.enums.OrderStatus;
import com.kly.enums.TradeResultStatus;
import com.kly.req.UserConsumeRequest;
import com.kly.sc.api.application.constant.ApiRedisKeys;
import com.kly.sc.api.application.consts.Constants;
import com.kly.sc.api.application.controller.order.request.UserBehaviorLog;
import com.kly.sc.api.application.controller.user.UserController;
import com.kly.sc.api.application.controller.user.request.DoUserLikeRequest;
import com.kly.sc.api.application.enums.ApiResultStatus;
import com.kly.sc.api.application.helper.RequestLocalInfo;
import com.kly.sc.api.application.service.utils.BaseComponent;
import com.kly.sc.api.application.service.utils.RedisService;
import com.kly.sc.api.application.utils.RpcUtils;
import com.kly.sc.api.infras.enums.RestCodeEnum;
import com.kly.sc.api.infras.exception.ApplicationException;
import com.kly.sc.api.infras.utils.StringUtils;
import com.kly.service.MemberBenefitsService;
import com.kly.service.MemberService;
import com.kly.service.TOrderService;
import com.kly.service.UserVasPurchasesService;
import com.kly.user.chatterService.ChatterUserService;
import com.kly.user.dto.*;
import com.kly.user.dto.chatter.response.UserChatterDto;
import com.kly.user.dto.ppv.PpvLogDto;
import com.kly.user.enums.*;
import com.kly.user.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;


/**
 * 付费服务
 */
@RestController
@RequestMapping("api/benefits")
public class PaidFeaturesController extends BaseComponent {

    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    MemberBenefitsService memberBenefitsService;
    @Resource
    UserVasPurchasesService userVasPurchasesService;
    @Resource
    BehaviorService behaviorService;
    @Resource
    MemberService memberService;
    @Resource
    RedisClient redisClient;
    @Resource
    RedisService redisService;
    @Resource
    OtherService otherService;
    @Resource
    private WlmService wlmService;
    @Resource
    private UserService userService;
    @Resource
    private UserController userController;
    @Resource
    private AppsflyerService appsflyerService;
    @Resource
    PPVLogService ppvLogService;
    @NacosValue(value = "${reduce.benefit.check:false}", autoRefreshed = true)
    private Boolean reduceBenefitCheck;
    @NacosValue(value = "${reduce.benefit.check2:false}", autoRefreshed = true)
    private Boolean reduceBenefitCheck2;
    @Resource
    TOrderService tOrderService;
    /**
     * ios 提审版标志
     */
    private final static String auth_version = "2";

    private static final String FORMAT = "yyyy-MM-dd HH:mm:ss";

    private static final Integer ONE = 1;

    @Resource
    ChatterUserService chatterUserService;



    /**
     * 是否第一次操作
     *
     * @param userBehaviorLog 用户行为
     */
    @RequestMapping(value = "isFirstOperation")
    public Response isFirstTimeOperation(@Valid @RequestBody UserBehaviorLog userBehaviorLog, BindingResult results) {
        if (results.hasErrors()) {
            return Response.error(results.getAllErrors().get(0).getDefaultMessage());
        }
        String userCode = getCurrentUserCode();
        LogActionEnum logActionEnum = LogActionEnum.fromType(userBehaviorLog.getActionType());
        if (logActionEnum == null) {
            return Response.error("No such action type exists");
        }
        //查询是否第一次操作
        Response<Boolean> firstTimeOperation =
                behaviorService.isFirstTimeOperation(userCode, userBehaviorLog.getActionType());
        //是第一次操作则添加行为记录
        if (firstTimeOperation.isSuccess() && firstTimeOperation.getData()) {
            UserBehaviorReq behaviorReq = UserBehaviorReq.builder()
                    .actionType(userBehaviorLog.getActionType())
                    .userCode(userCode)
                    .userCodeOperated(userBehaviorLog.getUserCodeOperated())
                    .resultType(LogResultTypeEnum.PASS.getType()).build();
            behaviorService.doAction(behaviorReq);
        }
        return firstTimeOperation;
    }


    /**
     * @param reduceBenefits ReduceBenefitsDto.benefitCode    服务代码
     *                       ReduceBenefitsDto.memberCode     会员号
     * @param results        参数校验
     * @return 用户增值服务集合
     */
    @RequestMapping(value = "queryBenefits")
    Response queryUserBenefits(@Valid @RequestBody ReduceBenefitsDto reduceBenefits, BindingResult results) {
        String userCode = getCurrentUserCode();
        Response<List<UserVasPurchasesDto>> benefits = userVasPurchasesService.getUserPurchasesBenefits(
                userCode, reduceBenefits.getBenefitCode());
        if (!benefits.isSuccess()) {
            return Response.error(TradeResultStatus.NO_AVAILABLE_BENEFITS);
        }
        return benefits;
    }

    /**
     * 扣减服务次数
     *
     * @param reduceBenefits 扣减服务类型
     * @param results        参数校验
     * @return 扣减结果
     */
    @RequestMapping(value = "reduceBenefits")
    Response reduceUserBenefits(@Valid @RequestBody ReduceBenefitsDto reduceBenefits, BindingResult results) {

        logger.info("扣减服务次数传参:{}",JSONObject.toJSONString(reduceBenefits));
        final String from = RequestLocalInfo.getRequestBasicInfo().getFrom();
        // ios提审版
        if (StringUtils.isNotEmpty(from) && from.equals(auth_version)) {
            return Response.ok();
        }
        String userCode = RequestLocalInfo.getCurrentUser().getUserCode();

        try {
            if (reduceBenefitCheck) {
                logger.info("reduceUserBenefitsV2:{}", JSONObject.toJSONString(reduceBenefits));
                final Response<List<TOrderDto>> response = tOrderService.queryOrder(userCode);
                if (response != null && response.isSuccess()) {
                    final List<TOrderDto> orders = response.getData();
                    if (CollectionUtils.isNotEmpty(orders)) {
                        logger.info("reduceUserBenefitsV2, 存在订单，订单数量:{}, userCode:{}", orders.size(), userCode);
                        final boolean existsPaidSuccessOrder = orders.parallelStream().anyMatch(o -> OrderStatus.PAID.getStatus() == o.getStatus());
                        if (!existsPaidSuccessOrder) {
                            logger.info("reduceUserBenefitsV2, 不存在支付成功订单, userCode:{}", userCode);
                            if (reduceBenefitCheck2) {
                                final Response result = new Response();
                                result.put("code", 2002);
                                result.put("msg", "Available member benefits are empty");
                                result.put("success", false);
                                logger.error("reduceUserBenefitsV2, 扣减失败1，返回code:{}, userCode:{}", "20004", userCode);
                                return result;
                            }

                        }
                    } else {
                        if (reduceBenefitCheck2) {
                            final Response result = new Response();
                            result.put("code", 2002);
                            result.put("msg", "Available member benefits are empty");
                            result.put("success", false);
                            logger.error("reduceUserBenefitsV2, 扣减失败2，返回code:{}, userCode:{}", "20005", userCode);
                            return result;
                        }
                    }
                }
            }else{
                logger.info("reduceUserBenefitsV2,开关未打开");
            }
        } catch (Exception e) {
            logger.error("reduceUserBenefitsV2Error,userCode={}", userCode, e);
        }

        // 添加日志
        String requestId = IdUtil.randomUUID();
        addPPVLog(requestId, reduceBenefits, userCode);

        //如果benefitCode为null则抛出异常
        if (reduceBenefits.getBenefitCode() == null || StringUtils.isEmpty(reduceBenefits.getChatUserCode())) {
            logger.info("benefitCode或chatUserCode为空");
            return Response.error(ApiResultStatus.PARAMETER_VALIDATION_FAILED);
        }

        UserBaseDto userByUserCode = userService.getUserBaseInfo(reduceBenefits.getChatUserCode()).getData();
        if (userByUserCode == null) {
            throw new ApplicationException(RestCodeEnum.USER_NOT_EXIST_ERROR);
        }


        // 前端未获取到imageCode， 该字段传入的值为imageUrl, 需要单独处理
        setIfNoImageCode(reduceBenefits);

        //如果扣减福利为FLASH_CHAT则判断是否当前用户是存在缓存
        if (Benefits.FLASH_CHAT.getBenefitCode() == reduceBenefits.getBenefitCode()) {
            // 当前用户对目前用户发起flashchat记当
            Object object = redisClient.get(ApiRedisKeys.USER_REDUCE_BENEFITS.getValue(), userCode, reduceBenefits.getChatUserCode());
            // 存在记录，不作福利扣减（同一个人只在第一次flashchat时扣除福利）
            if (object != null) {
                logger.info("存在缓存key: " + RedisClient.format(ApiRedisKeys.USER_REDUCE_BENEFITS.getValue(), userCode, reduceBenefits.getChatUserCode()) + "\nvalue: " + object);
                return Response.ok();
            }
        }


        reduceBenefits.setUserCode(userCode);
        //对重复请求的图片权益扣减做去重
        if(StringUtils.isNotEmpty(reduceBenefits.getImageCode())){
            UserConsumeRequest userConsumeRequest = new UserConsumeRequest();
            userConsumeRequest.setUserCode(userCode);
            userConsumeRequest.setImageCode(reduceBenefits.getImageCode());
            logger.info("对解锁图片做校验的传入参数:{}",JSONObject.toJSONString(userConsumeRequest));
            int isRecord = userVasPurchasesService.getUserConsumptionRecord(userConsumeRequest);
            logger.info("对解锁图片做校验的返回参数:{}",isRecord);
            //大于等于1的时候 1小时内有相关图片解锁的不作消费记录生成和权益消费
            if(isRecord>=1){
                updateUnlockLog(reduceBenefits, requestId, 3, "");
                return Response.ok();
            }
        }


        //扣减用户增值服务如果成功返回扣减成功
        Response<String> stringResponse = userVasPurchasesService.reduceUserBenefits(reduceBenefits);
        if (stringResponse.isSuccess()) {
            logger.info("扣减用户福利成功: " + JSONUtil.toJsonStr(stringResponse));
            addUserUsageBenefits(userCode, reduceBenefits);
            updateUnlockLog(reduceBenefits, requestId, 1, "");
            return stringResponse;
        }
        //扣减会员服务，如果成功返回扣减成功
        Response<String> memberBenefits = memberBenefitsService.reduceMemberBenefits(reduceBenefits);
        if (memberBenefits.isSuccess()) {
            logger.info("扣减会员福利成功: " + JSONUtil.toJsonStr(stringResponse));
            addUserUsageBenefits(userCode, reduceBenefits);
            updateUnlockLog(reduceBenefits, requestId, 1, "");
            return memberBenefits;
        }
        //判断是否为会员，如果是会员则提示会员服务使用次数为0
        Response<MemberDto> memberInfo = memberService.getMemberInfo(userCode, getAppCode());

        logger.info("memberInfo:{}", JSONObject.toJSONString(memberInfo));
        if (memberInfo.isSuccess()) {
            // 兼容处理
            if ("2.5.3".equals(RequestLocalInfo.getRequestBasicInfo().getAppVersionName())) {
                final Response response = new Response();
                response.put("code", 2003);
                response.put("msg", "Available member benefits are empty");
                response.put("success", false);
                updateUnlockLog(reduceBenefits, requestId, 2, "Available member benefits are empty");
                return response;
            }
            updateUnlockLog(reduceBenefits, requestId, 2, memberBenefits.getMsg());
            return memberBenefits;
        } else if (Benefits.VIEW_PRIVATE_PHOTOS.getBenefitCode() == reduceBenefits.getBenefitCode() || Benefits.VIEW_PRIVATE_VIDEOS.getBenefitCode() == reduceBenefits.getBenefitCode()) {
            // 非会员扣减失败，发送消息到mechat进行汇总
            sendNoneVipMessageToConsole(reduceBenefits, userCode);
        }

        if ("2.5.3".equals(RequestLocalInfo.getRequestBasicInfo().getAppVersionName())) {
            final Integer code = memberInfo.getCode();
            final Response response = new Response();
            if (code == 2003) {
                response.put("code", 2002);
                response.put("msg", "The user is not a member.");
                response.put("success", false);
                updateUnlockLog(reduceBenefits, requestId, 2, "The user is not a member.");
                return response;
            }
        }

        // v3.8.0版本：会员、非会员无flashchat次数，都弹出购买道具窗口
        if (Benefits.FLASH_CHAT.getBenefitCode() == reduceBenefits.getBenefitCode()) {
            final Response response = new Response();
            if (memberInfo.getCode() == 2003) {
                response.put("code", 2002);
                response.put("msg", "The user is not a member.");
                response.put("success", false);
                updateUnlockLog(reduceBenefits, requestId, 2, "The user is not a member.");
                return response;
            }
        }



        updateUnlockLog(reduceBenefits, requestId, 2, memberInfo.getMsg());

        //不是会员返回非会员
        return memberInfo;

//        if (!stringResponse.isSuccess()) {
//            //查询会员记录，不存在则返回该用户非会员
//            Response<MemberDto> memberInfo = memberService.getMemberInfo(userCode);
//            if (memberInfo.isSuccess()) {
//                //扣减会员使用次数
//                reduceBenefits.setMemberCode(memberInfo.getData().getMemberCode());
//                return memberBenefitsService.reduceMemberBenefits(reduceBenefits);
//            } else {
//                //返回不是会员
//                return memberInfo;
//            }
//        } else {
//            //扣减增值服务使用次数成功
//            return stringResponse;
//        }

    }

    private void updateUnlockLog(ReduceBenefitsDto reduceBenefits, String requestId, Integer status, String result) {
        try {
            if (reduceBenefits.getChatterUserCode() == null) {
                final String chatterUserCode = getChatterUserCode(reduceBenefits);
                reduceBenefits.setChatterUserCode(chatterUserCode);
            }
            ppvLogService.updateResult(requestId, status, result, reduceBenefits.getImageCode(), reduceBenefits.getImageUrl(), reduceBenefits.getChatterUserCode());
        } catch (Exception e) {
            logger.error("updateUnlockLogError, request:{}, status:{}", JSONObject.toJSONString(reduceBenefits), status, e);
        }
    }

    private void addPPVLog(String requestId, ReduceBenefitsDto reduceBenefits, String userCode) {
        try {
            PpvLogDto dto = new PpvLogDto();
            dto.setRequestId(requestId);
            dto.setBenefitCode(reduceBenefits.getBenefitCode());
            dto.setUserCode(userCode);
            dto.setModelUserCode(reduceBenefits.getChatUserCode());
            dto.setMsgId(reduceBenefits.getMsgId());
            ppvLogService.addPPVLog(dto);
        } catch (Exception e) {
            logger.error("addPPVLogError, userCode:{}, request:{}", userCode, JSONObject.toJSONString(reduceBenefits), e);
        }
    }

    private void addConsumeRecordLock(ReduceBenefitsDto reduceBenefits) {

        if(StringUtils.isNotEmpty(reduceBenefits.getImageCode())){
            redisClient.set(ApiRedisKeys.USER_CONSUME_RECORD_LOCK.getValue(),reduceBenefits.getImageCode(), Constants.EFFECTIVE_IN_10_MINUTE,reduceBenefits.getUserCode(),reduceBenefits.getImageCode());
        }
    }

    private void sendNoneVipMessageToConsole(@RequestBody @Valid ReduceBenefitsDto reduceBenefits, String userCode) {
        try {
            final Response<UserChatterDto> chatter = chatterUserService.getChatter(reduceBenefits.getChatUserCode());
            if (!chatter.isSuccess() || chatter.getData() == null) {
                return;
            }
            Map<String, String> header = Maps.newHashMap();
            header.put("Content-Type", "application/json");
            header.put("basicParams", "{\"channel\":\"l1\",\"appCode\":\"sparksy\",\"appVersion\":12,\"token\":\"\"}");

            Map<String, Object> params = Maps.newHashMap();
            params.put("chatterCode", chatter.getData().getChatterUserCode());
            params.put("modelUserCode", reduceBenefits.getChatUserCode());
            params.put("userCode", userCode);
            // 1ppv会员提示 2会话
            params.put("type", 1);

            final String response = HttpUtil.postPageBody(getChatterApiUrl() + "/api/chat/sendVipMessageNotice", header, JSONObject.toJSONString(params));
            logger.info("发送非会员扣减成功信息到mechat, req:{}, res:{}", JSONObject.toJSONString(params), response);
        } catch (Exception e) {
            logger.error("发送非会员扣减失败信息到mechat失败，userCode:{}, modelUserCode:{}", userCode, reduceBenefits.getChatUserCode(), e);
        }
    }

    private void setIfNoImageCode(@RequestBody @Valid ReduceBenefitsDto reduceBenefits) {
        final String imageCode = reduceBenefits.getImageCode();
        if (StringUtils.isNotEmpty(imageCode) && imageCode.contains("https")) {
            reduceBenefits.setAllImageUrl(reduceBenefits.getImageCode());
            final AlbumDto albumDto = RpcUtils.getResult(userService.getUserImages(reduceBenefits.getChatUserCode(), AlbumsType.PRIVATE_ALBUMS.getType()));
            if (albumDto == null || CollectionUtils.isEmpty(albumDto.getImages())) {
                logger.error("No images found, userCode:{}, imageCode:{}", reduceBenefits.getChatUserCode(), imageCode);
                throw new ApplicationException("No images found");
            }
            ImagesDto imagesDto = albumDto.getImages().stream().filter(o -> imageCode.contains(o.getImageUrl())).findFirst().orElse(null);
            if (imagesDto == null) {
                logger.error("No images found, userCode:{}, imageCode:{}", reduceBenefits.getChatUserCode(), imageCode);
                throw new ApplicationException("No images found");
            }
            reduceBenefits.setImageCode(imagesDto.getImageCode());
            reduceBenefits.setImageUrl(otherService.removePrefix(imagesDto.getImageUrl()));
        }
    }


    private void addUserUsageBenefits(String userCode, ReduceBenefitsDto reduceBenefits) {

        // 获取一小时后时间(提供mechat相册照片倒记时使用)
        String dateTime = DateUtil.format(DateUtil.offsetHour(new Date(), ONE), FORMAT);
        if ( StringUtils.isNotEmpty(reduceBenefits.getChatUserCode()) && StringUtils.isNotEmpty(reduceBenefits.getImageCode())) {
            //添加已查看图片记录,缓存1天。并且删除未查看记录
            redisClient.hPut(ApiRedisKeys.VIEW_PRIVATE_ALBUMS.getValue(),
                    reduceBenefits.getImageCode(), dateTime, reduceBenefits.getChatUserCode(), userCode);
            logger.info("添加缓存key: " + RedisClient.format(ApiRedisKeys.VIEW_PRIVATE_ALBUMS.getValue(), reduceBenefits.getChatUserCode(), userCode)
                    + "\nHashKey: " + reduceBenefits.getImageCode() + "\nHashValue" + dateTime);
            redisClient.expire(ApiRedisKeys.VIEW_PRIVATE_ALBUMS.getValue(),
                    (int) RememberTime.ONE_HOURS.getTime(), reduceBenefits.getChatUserCode(), userCode);
            long result = redisService.hDel(ApiRedisKeys.NOT_VIEWED_PRIVATE_ALBUM.getValue(),
                    reduceBenefits.getAllImageUrl(), reduceBenefits.getChatUserCode(), userCode);
            logger.info("rizhi11" + reduceBenefits.getAllImageUrl());
        }

        try {
            final String chatterUserCode = getChatterUserCode(reduceBenefits);
            if (StringUtils.isNotEmpty(chatterUserCode)) {
                reduceBenefits.setChatterUserCode(chatterUserCode);
            }

            // 同一个人第一次flashchat扣减福利
            if (Benefits.FLASH_CHAT.getBenefitCode() == reduceBenefits.getBenefitCode()){
                redisClient.set(ApiRedisKeys.USER_REDUCE_BENEFITS.getValue(), userCode, RememberTime.ONE_WEEK.getTime(), userCode, reduceBenefits.getChatUserCode());

                // 推送到appsflyer
//                asyncPushToAppsFlyer(userCode);

                // 添加建联记录
                addConnectRecord(userCode, reduceBenefits);
            }

            //添加用户消费记录
            addReduceRecord(userCode, reduceBenefits);

        }catch (Exception e){
            logger.error ("addUserUsageBenefits error: {}" + JSONUtil.toJsonStr(reduceBenefits),e);
        }

    }

    private void addReduceRecord(String userCode, ReduceBenefitsDto reduceBenefits) {
        // TODO: 2023/10/26 需要判重
        userVasPurchasesService.addUserConsumptionRecord(reduceBenefits);
        addConsumeRecords(userCode, reduceBenefits);
    }

    private void addConnectRecord(String userCode, ReduceBenefitsDto reduceBenefits) {
        AddWlmReq addWlmReq = new AddWlmReq();
        addWlmReq.setUserCode(userCode);
        addWlmReq.setUserCodeFriend(reduceBenefits.getChatUserCode());
        wlmService.connectByFlashChat(addWlmReq);
    }

    private void addConsumeRecords(String userCode, ReduceBenefitsDto reduceBenefits) {
        AddWlmReq addWlmReq = new AddWlmReq();
        addWlmReq.setUserCode(userCode);
        addWlmReq.setUserCodeFriend(reduceBenefits.getChatUserCode());
        addWlmReq.setChatterUserCode(reduceBenefits.getChatterUserCode());
        addWlmReq.setLikeType(reduceBenefits.getBenefitCode());
        wlmService.addUserUsageBenefits(addWlmReq);
    }

    private String getChatterUserCode(ReduceBenefitsDto reduceBenefits) {
        try {
            String chatterUserCode = null;
            final Response<UserChatterDto> chatterRsp = chatterUserService.getChatter(reduceBenefits.getChatUserCode());
            if (chatterRsp != null && chatterRsp.isSuccess()) {
                final UserChatterDto chatter = chatterRsp.getData();
                if (chatter != null) {
                    chatterUserCode = chatter.getChatterUserCode();
                }
            }
            return chatterUserCode;
        } catch (Exception e) {
            logger.error("getChatterUserCodeFailed, reduceBenefits:{}", JSONObject.toJSONString(reduceBenefits));
        }
        return null;
    }

    /**
     * 推送建数据到appsflyer
     */
    private void asyncPushToAppsFlyer(String userCode) {
        try {
            logger.info("asyncPushToAppsFlyerStart, userCode:{}", userCode);
            final HashMap<String, Object> pushData = Maps.newHashMap();
            pushData.put("userCode", userCode);
            appsflyerService.asyncTraceEvent(AppsFlyerEventDefType.Connect, pushData);
        } catch (Exception e) {
            logger.error("asyncPushToAppsFlyerFailed, userCode:{}", userCode, e);
        }
    }


    private ApiRedisKeys getApiRedisKeyFromLogActionEnum(LogActionEnum logActionEnum) {
        switch (logActionEnum) {
            case FIRST_FLASH_CHAT:
                return ApiRedisKeys.FIRST_FLASH_CHAT;
            case FIRST_PRIVATE_PHOTO:
                return ApiRedisKeys.FIRST_VIEW_PRIVATE_PHOTOS;
            case FIRST_PRIVATE_VIDEO:
                return ApiRedisKeys.FIRST_VIEW_PRIVATE_VIDEOS;
            default:
                throw new ApplicationException("Invalid LogActionEnum: " + logActionEnum);
        }
    }


    @RequestMapping(value = "reduceWLM")
    Response reduceWLM(@Valid @RequestBody DoUserLikeRequest doUserLikeRequest, BindingResult results) {
        // Check for errors in the request
        if (results.hasErrors()) {
            return Response.error(ApiResultStatus.PARAMETER_VALIDATION_FAILED);
        }

        String userCode = RequestLocalInfo.getCurrentUser().getUserCode();
        MemberDto memberDto = retrieveMemberFromCacheOrService(userCode);

        // If the member exists, return early
        if (memberDto != null) {
            logger.info("此用户为会员用户 userCode: " + userCode + "\nmemberDto:" + JSONUtil.toJsonStr(memberDto));
            userController.wlmLIke(doUserLikeRequest);
            return Response.ok();
        }

        // If likeType is DO_NOT, return an error
        if (doUserLikeRequest.getLikeType() == LikeEnum.DO_NOT.getType()) {
            logger.info("非会员禁止Wlm使用不喜欢功能 userCode: " + userCode);
            return Response.error(TradeResultStatus.NO_MEMBER);
        }

        // Create and setup ReduceBenefitsDto
        ReduceBenefitsDto reduceBenefits = new ReduceBenefitsDto();
        reduceBenefits.setUserCode(userCode);
        reduceBenefits.setBenefitCode(Benefits.WHO_LIKES_ME.getBenefitCode());


        Response<String> stringResponse = userVasPurchasesService.reduceUserBenefits(reduceBenefits);
        if (stringResponse.isSuccess()) {
            // 非flashchat建联标识
            doUserLikeRequest.setFlashchatFlag(Boolean.FALSE);
            userController.wlmLIke(doUserLikeRequest);
            logger.info("扣减wlm成功: " + JSONUtil.toJsonStr(stringResponse));

            return Response.ok();
        }

        return Response.error(TradeResultStatus.NO_MEMBER);

    }

}
